package com.ourteam.frame.controller;

import java.io.BufferedReader;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestParam;

import com.ourteam.frame.web.ApplicationModel;

import net.service.SpringContextAgent;

public class AbstractServiceController {

	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(AbstractServiceController.class);

	// @RequestMapping("/error")
	public String error(@RequestParam(required = false) String code, @RequestParam(required = false) String state,
			HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {

		return "error/500";

	}

	protected long getSubmitterId(HttpServletRequest request) {
		String submitterId = request.getParameter("submitterId");
		if (StringUtils.isNotBlank(submitterId)) {
			return Long.parseLong(submitterId);
		} else {
			return 0;
		}
	}

	protected String getLoginUserAccount() {

		Subject subject = SecurityUtils.getSubject();

		ApplicationModel appModel = (ApplicationModel) subject.getPrincipal();

		return appModel.getUserAccount();
	}

	protected String getLoginUserName() {

		Subject subject = SecurityUtils.getSubject();

		ApplicationModel appModel = (ApplicationModel) subject.getPrincipal();

		return appModel.getUserName();
	}

	protected long getLoginUserId() {

		Subject subject = SecurityUtils.getSubject();

		ApplicationModel appModel = (ApplicationModel) subject.getPrincipal();

		return appModel.getUserId();
	}


	protected String readJSONStringFromRequestBody(HttpServletRequest request) {
		StringBuffer json = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null) {
				json.append(line);
			}
		} catch (Exception e) {
			logger.error(" Error reading JSON string: " + e.toString());
		}
		return json.toString();
	}

	protected <T> T populateFormBean(T formBeanInstance, HttpServletRequest request) throws Exception {

		Map<String, String[]> map = request.getParameterMap();

		Set<String> keySet = map.keySet();

		for (Iterator<String> iterator = keySet.iterator(); iterator.hasNext();) {
			String key = iterator.next();

			if (PropertyUtils.isWriteable(formBeanInstance, key)) {

				String[] values = map.get(key);

				Class<?> dataType = PropertyUtils.getPropertyType(formBeanInstance, key);

				if (ArrayUtils.isNotEmpty(values)) {

					if (values.length == 1) {

						if (StringUtils.isNotBlank(values[0])) {

							if (dataType.equals(Date.class)) {

								PropertyUtils.setProperty(formBeanInstance, key,
										DateUtils.parseDate(values[0], new String[] { "yyyy-MM-dd", "yyyy/MM/dd" }));
							} else if (dataType.equals(long.class)) {
								PropertyUtils.setProperty(formBeanInstance, key, Long.parseLong(values[0]));
							} else if (dataType.equals(int.class)) {
								PropertyUtils.setProperty(formBeanInstance, key, Integer.parseInt(values[0]));
							} else {
								PropertyUtils.setProperty(formBeanInstance, key, values[0]);
							}
						}

					} else {

						if (dataType.equals(long[].class)) {
							long[] ids = new long[values.length];
							for (int i = 0; i < ids.length; i++) {
								ids[i] = Long.parseLong(values[i]);
								PropertyUtils.setProperty(formBeanInstance, key, ids);
							}
						} else {
							PropertyUtils.setProperty(formBeanInstance, key, values);
						}

					}
				}

			}
		}

		return formBeanInstance;
	}

	public String getConfig(String name) throws Exception {
		return SpringContextAgent.getApplicationContext().getBean("configProperties", Properties.class)
				.getProperty(name);
	}

	public String getConfig(String name, String defaultValue) throws Exception {
		return SpringContextAgent.getApplicationContext().getBean("configProperties", Properties.class)
				.getProperty(name, defaultValue);
	}

	public String getLocalMessage(String key, Object[] args, String defaltMessage, Locale locale) {
		return SpringContextAgent.getApplicationContext().getMessage(key, args, defaltMessage, locale);
	}

	public String getLocalMessage(String messageKey, String defaultValue, Locale locale) {
		return getLocalMessage(messageKey, null, defaultValue, locale);
	}

	public String getLocalMessage(String key, Object[] args, Locale locale) {
		return getLocalMessage(key, args, null, locale);
	}

	public String getLocalMessage(String messageKey, Locale locale) {
		return getLocalMessage(messageKey, null, null, locale);
	}

}
